import { Graph, Shape } from '@antv/x6';
import { createDnd } from './dnd';
import { getUrlParam } from '@/utils/index.js';

import * as nodeApi from '@/apis/bpnmNode.api.js';
import '@/registors/index.js';

export function init(selector, option) {
  const wrapDom = document.documentElement.querySelector('.dnd-wrap');
  const graph = new Graph({
    container: document.getElementById(selector),
    width: document.documentElement.offsetWidth - (wrapDom && wrapDom.offsetWidth || -4) - 4,
    height: document.documentElement.offsetHeight - 55,
    grid: true,
    snapline: true,
    /* scroller: {
       enabled: true,
       pannable: true,
       pageVisible: false,
       pageBreak: false,
     },*/
    panning: {
      enabled: true,
    },
    mousewheel: {
      enabled: true,
      modifiers: 'ctrl',
      factor: 1.1,
      maxScale: 5,
      minScale: 0.5,
    },
    
    connecting: {
      router: {
        //name: 'orth',
        /*name: 'manhattan',
        args: {
          padding: 1,
        },*/
        /*  name: 'er',
          args: {
            offset: 'center',
          },*/
        
        name: 'manhattan',
        args: {
          offset: 10,
        },
        
      },
      connector: {
        name: 'rounded',
        args: {
          radius: 8,
        },
      },
      anchor: 'center',
      connectionPoint: 'anchor',
      allowBlank: false,
      snap: true,
      allowMulti: false,
      createEdge() {
        /*        return new Shape.Edge({
                  attrs: {
                    line: {
                      stroke: '#222',
                      strokeWidth: 2,
                      targetMarker: {
                        name: 'block',
                        width: 12,
                        height: 8,
                      },
                    },
                  },
                  zIndex: 0,
                });*/
        return new Shape.Edge({
          shape: 'bpmn-edge',
        });
      },
      validateConnection({ targetMagnet }) {
        return !!targetMagnet;
      },
      highlight: true,
    },
    
    /*
        highlighting: {
          magnetAdsorbed: {
            name: 'stroke',
            args: {
              attrs: {
                fill: '#5F95FF',
                stroke: '#5F95FF',
              },
            },
          },
        },*/
    //keyboard: true,
    
  });
  
  
  var dnd = createDnd(graph, option);
  
  // setTimeout(()=>{
  //     rect.attr("label/text",'')
  // },1000)
  
  
  graph.on('node:mouseenter', ({ node }) => {
    // node.addTools([{
    //     name: 'button-remove'
    // }])
    node.setPortProp('port1', 'attrs/circle', { r: 4 });
    node.setPortProp('port2', 'attrs/circle', { r: 4 });
    node.setPortProp('port3', 'attrs/circle', { r: 4 });
    node.setPortProp('port4', 'attrs/circle', { r: 4 });
    
  });
  graph.on('node:mouseleave', ({ node }) => {
    // node.removeTool('button-remove')
    node.setPortProp('port1', 'attrs/circle', { r: 0 });
    node.setPortProp('port2', 'attrs/circle', { r: 0 });
    node.setPortProp('port3', 'attrs/circle', { r: 0 });
    node.setPortProp('port4', 'attrs/circle', { r: 0 });
    
  });
  

  
  
  // 双击进入编辑模式
  graph.on('node:dblclick', ({ node, e }) => {
    node.addTools({
      name: 'node-editor',
      args: {
        event: e,
      },
    });
  });
  
  
  /* graph.on('activity:click', ({ view,node, e }) => {
     //console.log('noded click',node);
   })*/
  
  graph.on('bpmn-edge:click', ({ view, node, e }) => {
    //console.log('noded click',node);
  });
  
  graph.on('node:click', ({ node, e }) => {
    //console.log('noded click',node);
    removeAllBoundary();
    node.addTools([{ name: 'boundary' }]);
    option && option.click && option.click(node);
  });
  
  graph.on('edge:click', ({ edge, e }) => {
    //console.log('noded click',node);
    //edge.setLabelAt(0,"点击就有 label")
    removeAllBoundary();
    edge.addTools([{ name: 'boundary' }]);
    option && option.click && option.click(edge);
    
  });
  graph.on('edge:mouseenter', ({ edge, e }) => {
    console.log('edge:mouseent', edge, edge && edge.data);
    var biaodashi = (edge.data && edge.data.use123) || '';
    edge.setAttrByPath('signText/text', biaodashi);
    edge.setAttrByPath('signText/fontSize', 20);
    edge.setAttrByPath('line/strokeWidth', 10);
  });
  graph.on('edge:mouseleave', ({ edge, e }) => {
    console.log('edge:mouseleave', edge);
    edge.setAttrByPath('signText/text', '');
    edge.setAttrByPath('line/strokeWidth', 2);
  });
  /*节点生产*/
  graph.on('edge:connected', async ({ isNew, edge }) => {
    console.log('edge:connected', edge);
    if (isNew) {
      const sourceNode = edge.getSourceCell();
      const targetNode = edge.getTargetCell();
      //targetCell.updateData({ parentNodeCode: source && source.id });
      var result = await nodeApi.addLine({
        bpmId: getUrlParam('bpmId'),
        sourceNodeId: sourceNode && sourceNode.data && sourceNode.data.id,
        targetNodeId: targetNode && targetNode.data && targetNode.data.id,
      });
      if (result && result.success) {
        //得到 线段id
        var addId = `${result.data || ''}`;
        console.log('线段id', addId);
        edge.updateData({
          ...edge.getData(),
          sourceNodeId: sourceNode && sourceNode.data && sourceNode.data.id,
          targetNodeId: targetNode && targetNode.data && targetNode.data.id,
          id: addId,
        });
        
      }
    }
    
    
  });
  
  function removeAllBoundary() {
    var nodes = graph.getNodes();
    for (let i = 0; i < nodes.length; i++) {
      nodes[i].removeTool('boundary');
    }
    var edges = graph.getEdges();
    for (let i = 0; i < edges.length; i++) {
      edges[i].removeTool('boundary');
    }
  }
  
  /*  graph.on('blank:click', ({ edge, e }) => {
      removeAllBoundary()
    })
    */
  
  // region  节点添加 删除
  graph.on('cell:added', ({ cell, e }) => {
    if (cell.shape == 'activity' ||
      cell.shape == 'end-event' ||
      cell.shape == 'start-event') {
      var tempid = sessionStorage.getItem('tempId');
      console.log('update data id', tempid);
      cell.updateData({ id: tempid });
    }
  });
  
  // endregion
  
  
  function removeLeftMenu() {
    document.documentElement.querySelector('#leftMenu').style.display = 'none';
  }
  
  function registgerMenu() {
    document.documentElement.removeEventListener('click', removeLeftMenu);
    document.documentElement.addEventListener('click', removeLeftMenu);
  }
  
  graph.on('cell:contextmenu', ({ cell, e }) => {
    console.log('contextmenu', e, e.clientX, e.clientY, cell, cell.id);
    document.documentElement.querySelector('#leftMenu').style.display = 'block';
    document.documentElement.querySelector('#leftMenu').style.top = (e.clientY - 44) + 'px';
    document.documentElement.querySelector('#leftMenu').style.left = e.clientX + 'px';
    sessionStorage.setItem('contextmenu_current_node_id', cell && cell.id);
    registgerMenu();
    
  });
  
  
  // graph.fromJSON(data1)
  
  
  return {
    graph,
    dnd,
  };
  
  // graph.fromJSON(data)
}

